package cn.liontalk.ObserverPattern;

import java.util.ArrayList;

/**
 * Created by ZhouZhe on 2018/5/19.
 */
public class WeatherData implements Subject {


    private ArrayList Observers;

    private float temperture;

    private float humidity;

    private float pressure;

    public WeatherData(){
        Observers = new ArrayList();
    }


    /**
     * 注册观察者
     * @param observer
     */
    @Override
    public void registerObserver(Observer observer) {
        Observers.add(observer);
    }


    /**
     * 取消注册的观察者
     * @param observer
     */
    @Override
    public void removeObserver(Observer observer) {
       int i = Observers.indexOf(observer);
       if(i>0){
           Observers.remove(i);
       }
    }


    @Override
    public void notifyObservers() {
        for(int i=0;i<Observers.size();i++){
            Observer observer = (Observer) Observers.get(i);
            observer.update(temperture,humidity,pressure);
        }
    }

    /**
     * 当数据变化的时候，更新数据通知观察者
     */
    public void  measurementChanged(){
        notifyObservers();
    }


    public void setMeasurements(float temperture,float humidity,float pressure){
        this.temperture = temperture;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementChanged();
    }


}
